package org.example.emp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.emp.common.JwtUtils;
import org.example.emp.common.RsaUtils;
import org.example.emp.mapper.AdminMapper;
import org.example.emp.pojo.Admin;
import org.example.emp.pojo.Result;
import org.example.emp.pojo.UserToken;
import org.example.emp.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.ResourceUtils;

import java.io.FileNotFoundException;
import java.security.PrivateKey;
import java.security.PublicKey;

/**
 *
 * AdminServiceImpl类实现AdminService接口
 * 接口回调
 */
@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    /** 管理员登录功能
     *
     * @param admin 对象参数传递
     * @return
     */
    @Override
    public Result login(Admin admin) {
        //1.根据用户名查询数据库，返回admin对象
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username" , admin.getUsername());
        Admin loginAdmin = adminMapper.selectOne(queryWrapper);
        //2.如果用户名不存在，则直接返回登录失败
        if(loginAdmin == null){
            return new Result(100 , "管理员不存在");
        }
        if(!admin.getUsername().equals(loginAdmin.getUsername())){
            return new Result(100 , "管理员不存在");
        }
        //3.如果用户存在，则比较密码（MD5）
        if(!DigestUtils.md5DigestAsHex(admin.getPassword().getBytes()).equals(loginAdmin.getPassword())){
            return new Result(100 , "密码不正确");
        }
        //4.如果登陆成功，则颁发Token（利用私钥生成Token）
        admin.setPassword("");
        try {
            PrivateKey privateKey = RsaUtils.getPrivateKey(ResourceUtils.getFile("classpath:rsa.pri").getPath());
            String token = JwtUtils.generateTokenExpireInMinutes(admin,privateKey,30);
            UserToken userToken = new UserToken();
            userToken.setToken(token);
            return new Result(0 , "登陆成功" , userToken);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(100 , "token生成失败");
        }
    }

    @Override
    public Result getInfo(String token) throws Exception {
        PublicKey publicKey = RsaUtils.getPublicKey(ResourceUtils.getFile("classpath:rsa.pub").getPath());
        Admin admin = (Admin) JwtUtils.getInfoFromToken(token, publicKey, Admin.class);
        UserToken userToken = new UserToken();
        userToken.setName(admin.getUsername());
        userToken.setAvatar("1111111111");
        return new Result<>(0 , "查询成功" , userToken);
    }
}
